<?php
class user{
	public $id = -1;
	public $username;
	public $last_refreshed;
	public $threshold = 0;
	public $current_cache_guid;
	public $current_page = 0;
	public $total_pages = 0;

	public static function get($username){
		if($result = db_query("SELECT * FROM user WHERE username ='%s'",$username)){

			$row = mysql_fetch_assoc($result);
			$user = new user();
			$user->id = $row["id"];
			$user->username = $row["username"];
			$user->last_refreshed = $row["last_refreshed"];
			$user->threshold = $row["threshold"];
			$user->current_cache_guid = $row["current_cache_guid"];
			$user->current_page = $row["current_page"];
			$user->total_pages = $row["total_pages"];
			return $user;
		}else{
			return false;
		}
	}

	function continue_cache(){
		return $this->current_page < $this->total_pages || $this->total_pages == 0;
	}
	function can_refresh(){
		$sql = "SELECT COUNT(*) FROM user WHERE username = '%s' AND last_refreshed < '%s'";
		if(db_scalar_query($sql, array($this->username,date ("Y-m-d H:i:s",time()-(60*60)))) > 0){
			return true;
		}
		return false;
	}

	function clear_cache(){
		db_query("DELETE FROM library_cache WHERE user_id = %d",$this->id);
		$this->total_pages = 0;		
		$this->current_page = 0;
		$this->current_cache_guid = uniqid();
		$this->save();
	}

	function delete(){
		clear_cache();
		db_query("DELETE FROM user_artist WHERE user_id = %d",$this->id);
		db_query("DELETE FROM user WHERE user_id = %d",$this->id);
		$this->id = -1;
	}


	function save(){
		$sql = "SELECT COUNT(*) FROM user WHERE username = '%s'";
		if(db_scalar_query($sql, $this->username) > 0){
			$sql = "UPDATE user 
				SET threshold=%d,
				last_refreshed='%s',
				current_cache_guid = '%s',
				current_page = %d,
				total_pages = %d
				WHERE username ='%s'";
			db_query($sql, array(
			$this->threshold,
			$this->last_refreshed,
			$this->current_cache_guid,
			$this->current_page,
			$this->total_pages,
			$this->username));
		}else{
			$sql = "INSERT INTO user(username,created,last_accessed,last_refreshed,threshold,current_cache_guid,current_page,total_pages) VALUES ('%s', NOW(),NOW(),'1977-10-17',%d,'%s',%d,%d)";
			$this->id = db_insert_id_query($sql,array(
			$this->username,
			$this->threshold,
			$this->current_cache_guid,
			$this->current_page,
			$this->total_pages,
			));
		}
		return $this->id;
	}
	
	function tags(){
		$sql = "SELECT ag.tag, SUM( ua.playcount ) AS playcount
FROM user_artist ua
INNER JOIN artist_genre ag ON ua.artist_id = ag.artist_id
WHERE ua.user_id = %d
GROUP BY ag.tag	
ORDER BY ag.tag";

		$tags = array();
		if($result = db_query($sql,$this->id)){
			while($row = mysql_fetch_assoc($result)){
				$tags[] = $row;
			}
		}
		return $tags;
	
	}

}
